package cn.book.bus.config;

import org.apache.catalina.valves.ErrorReportValve;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.embedded.tomcat.TomcatContextCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.IOException;

@Configuration
public class TomcatConfig {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Bean
    public TomcatContextCustomizer myTomcatContextCustomizer() {
        return context -> {
            String tomcatTempPath = context.getCatalinaBase().getPath();
            logger.info("tomcat目录：{}", tomcatTempPath);
            String path = tomcatTempPath + "/error/404.html";
            ClassPathResource cr = new ClassPathResource("error/404.html");
            if (cr.exists()) {
                File file404 = new File(path);
                if (!file404.exists()) {
                    try {
                        FileCopyUtils.copy(cr.getFile(), file404);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            ErrorReportValve valve = new ErrorReportValve();
            valve.setProperty("errorCode.404", path);
            valve.setShowServerInfo(false);
            valve.setShowReport(false);
            valve.setAsyncSupported(true);
            context.getParent().getPipeline().addValve(valve);
            context.getPipeline().addValve(valve);
        };
    }
}
